<template>
  <div class="archive-text__page">
    <coverModule :cover="archiveForm.cover" @change="coverChangeHandler" class="cover-module__item" />
    <el-input class="title__item" placeholder="请输入标题 (建议30字以内)" v-model="archiveForm.title" />
    <editorModule class="editor__item" @change="editorContentChangeHandler" @upload="editorUploadHandler" ref="editor" />
    <el-form label-position="top" size="mini">
      <el-form-item label="文章分类">
        <el-select placeholder="请选择" v-model="archiveForm.cid">
          <el-option :key="index" :label="classify.name" :value="classify.cid" v-for="(classify,index) in classifyList" />
        </el-select>
      </el-form-item>
      <el-form-item label="文章推荐语">
        <el-input :rows="4" class="desc__item" placeholder="推荐语会在动态中展示，有趣的描述更容易被小编推荐为热门动态哦～(=ﾟωﾟ)ﾉ" resize="none" type="textarea" v-model="archiveForm.mark" />
      </el-form-item>
      <el-form-item label="附件管理">
        <attachmentModule :images="images" @delete="imageDeleteHandler" />
      </el-form-item>
      <el-form-item>
        <el-button @click="submit(true)" plain round type="primary">提交文章</el-button>&nbsp;&nbsp;
        <el-button @click="submit(false)" plain round type="success">存草稿</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
    getArchiveEditedAPI,
    getArchiveDetailAPI,
    createArchiveAPI,
    putArchiveAPI,
    submitExamineAPI,
    addArchiveMetaAPI,
    putArchiveMetaAPI,
    getArchiveImagesAPI,
} from '@/api/archive';
import { getClassifyAPI } from '@/api/term';
import { serverSimpleUploaderAPI, deleteResourceAPI } from '@/api/utils';
import coverModule from './components/cover.vue';
import editorModule from './components/editor.vue';
import attachmentModule from './components/attachment.vue';

export default {
    components: {
        coverModule,
        editorModule,
        attachmentModule,
    },
    data() {
        return {
            archiveType: 4,
            coverFile: null,
            images: [],
            classifyList: [],
            archiveForm: {
                aid: 0,
                cover: '',
                title: '',
                cid: 1,
                content: '',
                mark: '',
            },
        };
    },
    computed: {
        aid() {
            return this.archiveForm.aid;
        },
        editArchiveID() {
            return this.$route.params.aid;
        },
    },
    created() {
        this.main(); // 调用进入页面的主处理程序
        this.keyboardEcentBind();// 绑定键盘事件
    },
    destroyed() {
        this.keyboardEcentUnBind(); // 解绑键盘事件
    },
    methods: {
        keyboardEcentBind() {
            window.addEventListener('keydown', this.keyboardSave);
            window.addEventListener('keyup', this.keyboardRunAndClear);
        },
        keyboardEcentUnBind() {
            window.removeEventListener('keydown', this.keyboardSave);
            window.removeEventListener('keyup', this.keyboardRunAndClear);
        },
        keyboardSave(evt) {
            if (evt.ctrlKey && evt.keyCode === 83) evt.preventDefault(); // 取消浏览器默认 ctrl+s 事件
        },
        keyboardRunAndClear(evt) {
            if (evt.ctrlKey && evt.keyCode === 83) this.submit(false); // ctrl+s 保存
        },
        /** @进入页面的主处理程序 */
        async main() {
            // 这个程序已经超越之前的很多了,大大的跨了一步
            await this.getClassify(); // 1,获取分类信息
            if (this.editArchiveID) { // 2,判断是否在编辑稿件
                await this.getArchiveDetail(this.editArchiveID); // 2.0,获取待编辑稿件的信息
            } else {
                await this.getArchiveEdited(); //  2.1,尝试获取未提交稿件(获取稿件aid)
            }
            await this.getArchiveMeta(); // 3,尝试获取稿件的扩展信息
        },
        /** @获取文章稿件分类 */
        async getClassify() {
            const classifyResult = await getClassifyAPI(this.archiveType);
            this.classifyList = classifyResult.data;
        },
        /** @获取未提交稿件 */
        async getArchiveEdited() {
            const archiveEditedResult = await getArchiveEditedAPI(this.archiveType); // return {code:200, message:'xxx', data:Array(x)}
            if (archiveEditedResult.data.length > 0) {
                const { aid } = archiveEditedResult.data[0];
                this.archiveForm.aid = aid;
                await this.getArchiveDetail(aid);
            }
        },
        /** @获取稿件详情 */
        async getArchiveDetail(aid) {
            const archive = await getArchiveDetailAPI(aid);
            this.archiveForm = archive.data;
            this.$refs.editor.renderValue(this.archiveForm.content);
        },
        /** @创建空白稿件 */
        async createArchive() {
            if (this.aid > 0) return; // 如果有aid就不执行
            const createArchiveResult = await createArchiveAPI(this.archiveType);
            this.archiveForm.aid = createArchiveResult.data; // data=aid
        },
        /** @获取稿件的扩展信息 */
        async getArchiveMeta() {
            if (!this.aid) return; // 如果没有aid的话 就不进行操作了
            const { data } = await getArchiveImagesAPI(this.aid);
            this.images = data;
        },
        /** @储存头图文件 */
        coverChangeHandler(file) { // 这里储存文件
            this.coverFile = file;
        },
        /** @上传头图文件 */
        async  coverUploadHandler() {
            const file = this.coverFile;
            const uploadResult = await serverSimpleUploaderAPI(file, '/articleArchiveCover');
            // 这里面还有一步操作是, ! 调用一下他的富文本编辑器上传图片操作...  真的因为逻辑是一样的
            await this.editorUploadHandler(uploadResult.result.data.data);
            this.coverFile = null;
            return uploadResult.file_path;
        },
        /** @富文本编辑内容变动的时候暂存富文本编辑器内容 */
        editorContentChangeHandler(content) {
            this.archiveForm.content = content;
        },
        /** @富文本编辑器上传图片附件的时候 */
        async editorUploadHandler(resourceInfo) {
            const { rid } = resourceInfo;
            await this.createArchive(); // 尝试创建一个空白稿件
            if (!this.images) {
                this.images = [rid];
                await addArchiveMetaAPI(this.aid, { key: 'images', value: this.images.toString() });
            } else {
                this.images.push(rid);
                this.putArchiveMeta(this.images.toString());
            }
        },
        /** @修改稿件图片附件 */
        async putArchiveMeta(value) {
            await putArchiveMetaAPI(this.aid, { key: 'images', value });
        },
        /** @删除稿件图片附件 */
        async imageDeleteHandler({ value, imageTarget }) {
            await this.putArchiveMeta(value);
            await deleteResourceAPI(imageTarget.rid);
        },
        /** @提交文章稿件_存草稿 */
        async submit(isExamine) {
            if (this.coverFile) { // 如果有封面图, 就上传封面图
                this.archiveForm.cover = await this.coverUploadHandler();
            }
            try {
                await this.createArchive(); // 尝试创建一个空白稿件
                await putArchiveAPI(this.aid, this.archiveForm); // 使用修改作为提交草稿功能
                if (isExamine) { // 如果是提交审核,就执行这一部分
                    this.submitExamine();
                } else {
                    this.$message('稿件保存成功');
                }
            } catch (error) {
                console.error('稿件发布失败QAQ', error);
            }
        },
        async submitExamine() {
            await submitExamineAPI(this.aid);
            this.$router.replace({ name: 'ArticlesManager' }); // 跳转去稿件管理界面
        },
    },
};
</script>

<style lang="scss">
.archive-text__page {
  width: $baseWidth;
  margin: 0 auto 50px;
  padding: 0 20px;
  border: 1px solid #c9d8db;
  border-radius: 4px;
  overflow: hidden;
  .title__item {
    padding: 12px 50px 12px 0;
    > input {
      border: 0;
      font-size: 28px;
    }
  }
  .cover-module__item {
    margin: 0 -20px;
  }
  .editor__item {
    margin: 0 -20px;
  }
}
</style>
